import axios from 'axios'

// API配置
const API_BASE_URL = 'https://pro-api.solscan.io/v2.0'
const API_TOKEN = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjcmVhdGVkQXQiOjE3NTY4MzIzMDc5MjEsImVtYWlsIjoiOTI5MTQ0Mzg3QHFxLmNvbSIsImFjdGlvbiI6InRva2VuLWFwaSIsImFwaVZlcnNpb24iOiJ2MiIsImlhdCI6MTc1NjgzMjMwN30.SMO_QIYPvGgBFynqu2mynnU6BFfZLhs1x_ZNYSREg7c'

// 创建axios实例
const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 30000,
  headers: {
    'token': API_TOKEN,
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    console.log('API Request:', config.method?.toUpperCase(), config.url)
    return config
  },
  error => {
    console.error('API Request Error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    console.log('API Response:', response.status, response.config.url)
    return response
  },
  error => {
    console.error('API Response Error:', error.response?.status, error.message)
    return Promise.reject(error)
  }
)

// API方法
export const tokenAPI = {
  // 获取代币持有人 - 通过本地后端服务
  async getHolders(address, page = 1, pageSize = 100) {
    try {
      console.log(`正在请求本地后端服务: ${address}`)
      
      const response = await axios.get(`http://localhost:3001/api/token-holders/${address}`, {
        params: {
          limit: pageSize,
          orderby: 'amount_percentage',
          direction: 'desc'
        },
        timeout: 30000
      })
      
      console.log(`成功获取 ${response.data.data.items.length} 个持有人数据`)
      return response.data
      
    } catch (error) {
      console.error('获取持有人数据失败:', error.message)
      
      // 如果本地服务也失败了，返回模拟数据
      console.warn('本地服务请求失败，使用模拟数据')
      return this.getMockHoldersData()
    }
  },

  // 模拟数据方法
  getMockHoldersData() {
    const mockData = {
      success: true,
      data: {
        items: [
          {
            owner: '4eFAJp73mKWefZoJTn7CiPodta5UHvcSSHJeS31xTkzv',
            amount: 331061981.222121,
            percentage: 33.11,
            profit: 14178.37,
            profit_rate: 12.5,
            trade_type: 'buy',
            is_internal: false,
            source: 'TOP1',
            transfer_time: 1757418419
          },
          {
            owner: '7J2rKHs3j5ZBaaFFSRPpbKe7vxRLVpmz3YaSjtH8pT1P',
            amount: 195366400.0,
            percentage: 19.54,
            profit: 8500.25,
            profit_rate: 8.3,
            trade_type: 'buy',
            is_internal: false,
            source: '未知',
            transfer_time: 1757418000
          },
          {
            owner: '9PioBysuEs4gVhcaUYkzKDdW9BRcWqTek1Ew7bwdpump',
            amount: 150000000.0,
            percentage: 15.0,
            profit: 6500.0,
            profit_rate: 5.2,
            trade_type: 'sell',
            is_internal: true,
            source: '未知',
            transfer_time: 1757417500
          }
        ],
        total: 3
      }
    }
    return mockData
  },
  
  // 获取账户投资组合
  async getPortfolio(address) {
    try {
      const response = await api.get('/account/portfolio', {
        params: {
          address,
          exclude_low_score_tokens: true
        }
      })
      return response.data
    } catch (error) {
      console.error('获取投资组合失败:', error)
      throw error
    }
  },

  // 获取相同代币持有人数据
  async getSameTokenHolders(tokenAddress, page = 1, pageSize = 20) {
    try {
      const response = await api.get('/token/same-holders', {
        params: {
          tokenAddress,
          page,
          pageSize
        }
      })
      return response.data
    } catch (error) {
      console.error('获取相同代币持有人失败:', error)
      throw error
    }
  }
}

export default api
